<template>
  <div class="deposit-manage-page">
    <div class="page-header">
      <h1 class="page-title">충전 관리</h1>
      <p class="page-subtitle">사용자 충전 신청을 관리합니다</p>
    </div>
    
    <!-- 필터 조건 -->
    <el-card class="filter-card">
      <div class="filter-content">
        <el-form :model="filterForm" inline>
          <el-form-item label="상태">
            <el-select v-model="filterForm.status" placeholder="상태 선택" style="width: 120px">
              <el-option label="전체" value="all" />
              <el-option label="대기" value="PENDING" />
              <el-option label="승인 완료" value="CONFIRMED" />
              <el-option label="거절" value="FAILED" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="기간">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              start-placeholder="시작 날짜"
              end-placeholder="종료 날짜"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">검색</el-button>
            <el-button @click="handleReset">초기화</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <!-- 데이터 테이블 -->
    <el-card>
      <template #header>
        <div class="table-header">
          <span>충전 신청 목록</span>
          <div class="header-actions">
            <el-button
              type="primary"
              size="small"
              :loading="isExporting"
              @click="handleExportExcel"
            >
              Excel 내보내기
            </el-button>
            <el-button
              type="success"
              size="small"
              :disabled="selectedRecords.length === 0"
              @click="batchProcess('confirm')"
            >
              일괄 승인 ({{ selectedRecords.length }})
            </el-button>
            <el-button
              type="danger"
              size="small"
              :disabled="selectedRecords.length === 0"
              @click="batchProcess('reject')"
            >
              일괄 거절 ({{ selectedRecords.length }})
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="tableData" 
        v-loading="isLoading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="user.name" label="사용자 이름" width="120" />
        <el-table-column prop="user.idNumber" label="신분증 번호" width="160" />
        <el-table-column prop="amount" label="충전 금액" width="120">
          <template #default="{ row }">
            {{ formatAmount(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="nearAmount" label="대응 NEAR" width="140">
          <template #default="{ row }">
            <el-text
              :type="row.status === 'PENDING' ? 'warning' : 'info'"
              style="font-weight: 500"
            >
              {{ formatNearAmount(row.nearAmount) }}
            </el-text>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="상태" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="신청 시간" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="processedAt" label="처리 시간" width="160">
          <template #default="{ row }">
            {{ row.processedAt ? formatDateTime(row.processedAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="작업" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                v-if="row.status === 'PENDING'"
                type="success" 
                size="small"
                @click="handleProcess(row, 'confirm')"
              >
                승인
              </el-button>
              <el-button 
                v-if="row.status === 'PENDING'"
                type="danger" 
                size="small"
                @click="handleProcess(row, 'reject')"
              >
                거절
              </el-button>
              <el-button 
                type="primary" 
                size="small"
                @click="viewDetail(row)"
              >
                자세히
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 페이지네이션 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 처리 대화상자 -->
    <el-dialog
      v-model="showProcessDialog"
      :title="processDialogTitle"
      width="500px"
    >
      <el-form :model="processForm" label-width="100px">
        <el-form-item label="처리 유형">
          <el-tag :type="processForm.action === 'confirm' ? 'success' : 'danger'">
            {{ processForm.action === 'confirm' ? '충전 승인' : '충전 거절' }}
          </el-tag>
        </el-form-item>

        <!-- 新增：NEAR输入框（仅单笔审批时显示） -->
        <el-form-item
          v-if="processForm.action === 'confirm' && processForm.selectedIds.length === 1"
          label="실제 입금 NEAR"
          required
        >
          <el-input-number
            v-model="processForm.actualNearAmount"
            :precision="4"
            :step="0.1"
            :min="0"
            placeholder="실제 입금한 NEAR 수량 입력"
            style="width: 100%"
          />
          <el-alert
            :title="`참고 가격: ${nearPrice.toLocaleString('ko-KR')} ₩/NEAR`"
            type="info"
            :closable="false"
            show-icon
            style="margin-top: 8px"
          >
            <template #default>
              <div style="font-size: 12px;">
                <div>충전 금액: {{ getSelectedDepositAmount().toLocaleString('ko-KR') }} ₩</div>
                <div>권장 NEAR: {{ (getSelectedDepositAmount() / nearPrice).toFixed(4) }} NEAR</div>
              </div>
            </template>
          </el-alert>
        </el-form-item>

        <el-form-item label="메모">
          <el-input
            v-model="processForm.note"
            type="textarea"
            :rows="4"
            :placeholder="processForm.action === 'confirm' ? '승인 메모를 입력하세요 (선택 사항)' : '거절 사유를 입력하세요'"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showProcessDialog = false">취소</el-button>
          <el-button 
            :type="processForm.action === 'confirm' ? 'success' : 'danger'"
            @click="confirmProcess"
            :loading="isProcessing"
          >
            {{ processForm.action === 'confirm' ? '충전 승인' : '충전 거절' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'
import { exportToExcel, formatAmount as formatAmountForExcel, formatNearAmount as formatNearForExcel, formatDateTimeString } from '@/utils/exportExcel'
import type { ExportHeader } from '@/utils/exportExcel'

// 반응형 데이터
const tableData = ref<any[]>([])
const isLoading = ref(false)
const isExporting = ref(false) // 导出加载状态
const selectedRecords = ref<any[]>([])
const showProcessDialog = ref(false)
const isProcessing = ref(false)
const nearPrice = ref(0) // NEAR当前价格

const filterForm = reactive({
  status: 'all',
  dateRange: null as any
})

const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const processForm = reactive({
  action: '',
  note: '',
  selectedIds: [] as number[],
  actualNearAmount: 0 // 管理员输入的实际NEAR数量
})

// 계산 속성
const processDialogTitle = computed(() => {
  const actionText = processForm.action === 'confirm' ? '승인' : '거절'
  const count = processForm.selectedIds.length
  return count > 1 ? `충전 ${count}건 일괄 ${actionText}` : `충전 ${actionText}`
})

// 금액 포맷
const formatAmount = (amount: number): string => {
  return amount.toLocaleString('ko-KR') + ' ₩'
}

// NEAR数量格式化（保留4位小数）
const formatNearAmount = (amount: number): string => {
  return amount.toFixed(4) + ' NEAR'
}

// 날짜와 시간을 포맷
const formatDateTime = (dateTime: string): string => {
  return new Date(dateTime).toLocaleString('ko-KR')
}

// 상태 태그 타입 반환
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'CONFIRMED': return 'success'
    case 'FAILED': return 'danger'
    default: return 'info'
  }
}

// 상태 텍스트 반환
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '대기중',
    'CONFIRMED': '승인 확인',
    'FAILED': '거절',
    'CANCELLED': '취소'
  }
  return statusMap[status] || '알 수 없음'
}

// 데이터 로드
const loadData = async () => {
  try {
    isLoading.value = true
    
    const params: any = {
      page: pagination.page,
      limit: pagination.limit
    }
    
    if (filterForm.status !== 'all') {
      params.status = filterForm.status
    }
    
    if (filterForm.dateRange?.length === 2) {
      params.startDate = filterForm.dateRange[0]
      params.endDate = filterForm.dateRange[1]
    }
    
    const response = await request.get('/api/admin/deposit/list', { params }) as any

    if (response.success) {
      tableData.value = response.data.records
      pagination.total = response.data.pagination.total
      nearPrice.value = response.data.nearPrice || 0 // 保存NEAR价格
    }
  } catch (error) {
    console.error('데이터 로드 실패:', error)
    ElMessage.error('데이터 로드에 실패했습니다')
  } finally {
    isLoading.value = false
  }
}

// 검색
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 초기화
const handleReset = () => {
  filterForm.status = 'all'
  filterForm.dateRange = null
  pagination.page = 1
  loadData()
}

// Excel 내보내기
const handleExportExcel = async () => {
  try {
    isExporting.value = true

    // 构建导出参数（与当前筛选条件一致）
    const params: any = {
      exportAll: 'true' // 导出全部数据
    }

    if (filterForm.status !== 'all') {
      params.status = filterForm.status
    }

    if (filterForm.dateRange?.length === 2) {
      params.startDate = filterForm.dateRange[0]
      params.endDate = filterForm.dateRange[1]
    }

    // 调用API获取全部数据
    const response = await request.get('/api/admin/deposit/list', { params }) as any

    if (!response.success || !response.data.records) {
      ElMessage.error('데이터를 가져오는 데 실패했습니다')
      return
    }

    const records = response.data.records

    if (records.length === 0) {
      ElMessage.warning('내보낼 데이터가 없습니다')
      return
    }

    // 定义导出的列
    const headers: ExportHeader[] = [
      { label: 'ID', prop: 'id' },
      { label: '사용자 이름', prop: 'user.name' },
      { label: '신분증 번호', prop: 'user.idNumber' },
      {
        label: '충전 금액 (₩)',
        prop: 'amount',
        formatter: (val) => formatAmountForExcel(val)
      },
      {
        label: '대응 NEAR',
        prop: 'nearAmount',
        formatter: (val) => formatNearForExcel(val)
      },
      {
        label: '상태',
        prop: 'status',
        formatter: (val) => getStatusText(val)
      },
      {
        label: '신청 시간',
        prop: 'createdAt',
        formatter: (val) => formatDateTimeString(val)
      },
      {
        label: '처리 시간',
        prop: 'processedAt',
        formatter: (val) => val ? formatDateTimeString(val) : '-'
      }
    ]

    // 导出Excel
    exportToExcel({
      fileName: '충전관리',
      headers,
      data: records,
      sheetName: '충전 신청 목록'
    })

    ElMessage.success(`${records.length}건의 데이터를 성공적으로 내보냈습니다`)
  } catch (error) {
    console.error('Excel 내보내기 실패:', error)
    ElMessage.error('Excel 내보내기에 실패했습니다')
  } finally {
    isExporting.value = false
  }
}

// 선택 변경
const handleSelectionChange = (selection: any[]) => {
  selectedRecords.value = selection.filter(record => record.status === 'PENDING')
}

// 페이지 변경
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

// 단일 처리
const handleProcess = (record: any, action: string) => {
  processForm.action = action
  processForm.note = ''
  processForm.selectedIds = [record.id]

  // 如果是确认操作，计算推荐的NEAR数量
  if (action === 'confirm' && nearPrice.value > 0) {
    processForm.actualNearAmount = Number((Number(record.amount) / nearPrice.value).toFixed(4))
  } else {
    processForm.actualNearAmount = 0
  }

  showProcessDialog.value = true
}

// 일괄 처리
const batchProcess = (action: string) => {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning('처리할 항목을 선택해 주세요')
    return
  }
  
  processForm.action = action
  processForm.note = ''
  processForm.selectedIds = selectedRecords.value.map(record => record.id)
  showProcessDialog.value = true
}

// 처리 확정
const confirmProcess = async () => {
  try {
    // 验证：确认充值时必须输入NEAR数量
    if (processForm.action === 'confirm' && processForm.selectedIds.length === 1) {
      if (!processForm.actualNearAmount || processForm.actualNearAmount <= 0) {
        ElMessage.warning('실제 입금한 NEAR 수량을 입력하세요')
        return
      }
    }

    isProcessing.value = true

    const successMessage = processForm.action === 'confirm'
      ? '충전 승인이 완료되었습니다.'
      : '충전 거절이 완료되었습니다.'

    if (processForm.selectedIds.length === 1) {
      // 단일 처리
      const response = await request.post(`/api/admin/deposit/${processForm.selectedIds[0]}/process`, {
        action: processForm.action,
        note: processForm.note,
        actualNearAmount: processForm.actualNearAmount // 发送实际NEAR数量
      }) as any

      if (response.success) {
        ElMessage.success(successMessage)
      }
    } else {
      // 일괄 처리
      const response = await request.post('/api/admin/deposit/batch-process', {
        depositIds: processForm.selectedIds,
        action: processForm.action,
        note: processForm.note
      }) as any

      if (response.success) {
        ElMessage.success(successMessage)
      }
    }
    
    showProcessDialog.value = false
    selectedRecords.value = []
    loadData()
    
  } catch (error) {
    console.error('처리 실패:', error)
    ElMessage.error('처리에 실패했습니다')
  } finally {
    isProcessing.value = false
  }
}

// 获取选中充值记录的金额
const getSelectedDepositAmount = (): number => {
  if (processForm.selectedIds.length !== 1) return 0

  const selectedRecord = tableData.value.find(
    (record: any) => record.id === processForm.selectedIds[0]
  )

  return selectedRecord ? Number(selectedRecord.amount) : 0
}

// 상세 보기
const viewDetail = (record: any) => {
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <p><strong>사용자 정보</strong></p>
      <p>이름: ${record.user.name}</p>
      <p>신분증 번호: ${record.user.idNumber}</p>
      <p>휴대전화: ${record.user.mobileNumber}</p>
      <br>
      <p><strong>충전 정보</strong></p>
      <p>금액: ${formatAmount(record.amount)}</p>
      <p>신청 시간: ${formatDateTime(record.createdAt)}</p>
      <p>상태: ${getStatusText(record.status)}</p>
      ${record.adminNote ? `<p>메모: ${record.adminNote}</p>` : ''}
    </div>
  `, '충전 상세', {
    dangerouslyUseHTMLString: true
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.deposit-manage-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    font-size: 14px;
    color: #666;
    margin: 0;
  }
}

.filter-card {
  margin-bottom: 16px;

  .filter-content {
    padding: 16px;
  }
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  color: #333;

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}
</style>
